import Vue from 'vue';
import Router from 'vue-router';
import API from '@/api/userConfig';
import store from '@/store/index';
import Login from '@/pages/login/index';
import Index from '@/pages/board/index';

Vue.use(Router);
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      title: '登录',
    },
  },
  {
    path: '/index',
    alias: '/',
    name: 'index',
    component: Index,
    meta: {
      title: '云车间管理系统',
    },
    children: [],
  },
];

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes,
});

// 设置路由白名单
const whiteList = ['/login', '/workshop'];
router.beforeEach(async (to, from, next) => {
  window.scrollTo(0, 0);
  let userInfo = JSON.parse(localStorage.getItem('userInfo'));
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  // 判断本地缓存是否有用户信息
  if (userInfo && Object.keys(userInfo).length > 0) {
    // 获取user信息
    const res1 = await API.getRoleId({ phoneNumber: userInfo.username });
    if (res1.MsgCode != 0) {
      // this.$message.error('获取用户信息失败');
      return;
    }

    // 重新存储用户信息
    localStorage.setItem('userInfo', JSON.stringify(res1.Data));

    let res1UserName = res1.Data.username;
    // 通过接口获取最新路由表
    const res = await API.getUserResource({ username: res1UserName });
    if (res.MsgCode != 0) {
      this.$message.error('获取菜单列表失败');
      return;
    }

    let workShopCloudRoutes = res.Data.find((item) => {
      return item.appFlag == 'workShopCloud';
    });
    // 遍历权限中的授权页面
    if (workShopCloudRoutes) {
      store.commit('menu/saveMenuLists', workShopCloudRoutes.children);
    }
    store.commit('menu/setActiveMenuPath', { path: to.path });
    // 获取目标页面的按钮权限
    localStorage.setItem('userAuthorization', JSON.stringify(workShopCloudRoutes));
    // 判断router中有没有被授权的路由
    let hasRoutes = router.getRoutes();
    if (store.state.menu.allAuthRoutes.findIndex((item) => item.path == to.path) == -1) {
      // 如果目标页面不在授权路由表中,则前往login页面
      if (to.path === '/login') {
        next();
      } else {
        next({ name: 'login' });
      }
    } else {
      if (hasRoutes.findIndex((item) => item.path == to.path) == -1) {
        // 如果目标路由不在hasRoutes中,则重新加载路由表
        let authorizationRoutes = [];
        constantRoutes.forEach((item) => {
          if (item.name == 'index') {
            item.children = [...store.state.menu.allAuthRoutes];
          }
          authorizationRoutes.push(item);
        });
        router.addRoutes(authorizationRoutes);
        next({ ...to, replace: true });
      } else {
        // 如果是去登录界面
        if (to.path === '/login' || to.path === '/index' || to.path === '/') {
          // 直接跳转到菜单的第一项
          let path = store.state.menu.firstMenuPath;
          next({ path });
        } else {
          // 如果不是,前往目标页面,
          store.commit('menu/getAuthBtnlists', { path: to.path });
          next();
        }
      }
    }
  } else {
    // debugger;
    // 如果在免登录白名单中，直接进入,否则一律跳转到'login'界面
    if (whiteList.indexOf(to.path) != -1) {
      next();
    } else {
      next({ name: 'login' });
    }
  }
});

export default router;

// export default new Router({
//   routes: [
//     {
//       path: '/login',
//       name: 'login',
//       component: () => import('@/pages/login'),
//       meta: {
//         title: '云管家管理系统',
//       },
//     },
//     {
//       path: '',
//       component: (resolve) => require(['@/pages/board'], resolve),
//       redirect: '/board/workshop',
//       children: [
//         {
//           path: '/board/workshop',
//           name: 'workshop',
//           component: (resolve) => require(['@/pages/workshop'], resolve),
//           meta: {
//             title: '车间看板',
//           },
//         },
//         {
//           path: '/board/distributionMap',
//           name: 'distributionMap',
//           component: (resolve) => require(['@/pages/distributionMap'], resolve),
//           meta: {
//             title: '分布地图',
//           },
//         },
//         {
//           path: '/equipmentList',
//           name: 'equipmentList',
//           component: (resolve) => require(['@/pages/equipmentList'], resolve),
//           meta: {
//             title: '设备',
//           },
//         },
//         {
//           path: '/statistics',
//           name: 'statistics',
//           component: (resolve) => require(['@/pages/statistics'], resolve),
//           meta: {
//             title: '统计',
//           },
//         },
//         {
//           path: '/classeslist',
//           name: 'classesList',
//           component: (resolve) => require(['@/pages/classes/list'], resolve),
//           meta: {
//             title: '班次列表',
//           },
//         },
//         {
//           path: '/yieldDetails',
//           name: 'yieldDetails',
//           component: (resolve) => require(['@/pages/classes/yieldDetails'], resolve),
//           meta: {
//             title: '产量详情',
//           },
//         },
//         {
//           path: '/classessStatistics',
//           name: 'classessStatistics',
//           component: (resolve) => require(['@/pages/classes/statistics'], resolve),
//           meta: {
//             title: '班次统计',
//           },
//         },
//         {
//           path: '/classessScheduling',
//           name: 'classessScheduling',
//           component: (resolve) => require(['@/pages/classes/scheduling'], resolve),
//           meta: {
//             title: '排班',
//           },
//         },
//         {
//           path: '/orderAdd',
//           name: 'orderAdd',
//           component: (resolve) => require(['@/pages/orders/orderAdd'], resolve),
//           meta: {
//             title: '添加订单',
//           },
//         },
//         {
//           path: '/orderDetail',
//           name: 'orderDetail',
//           component: (resolve) => require(['@/pages/orders/orderDetail'], resolve),
//           meta: {
//             title: '订单详情',
//           },
//         },
//         {
//           path: '/cloudStorage',
//           name: 'cloudStorage',
//           component: (resolve) => require(['@/pages/cloudStorage'], resolve),
//           meta: {
//             title: '云盘',
//           },
//         },
//         {
//           path: '/cloudStorageDetail',
//           name: 'cloudStorageDetail',
//           component: (resolve) => require(['@/pages/cloudStorage/detail'], resolve),
//           meta: {
//             title: '云盘详情',
//           },
//         },
//         {
//           path: '/basicInformation',
//           name: 'basicInformation',
//           component: (resolve) => require(['@/pages/statisticalForm/basicInformation'], resolve),
//           meta: {
//             title: '基本信息',
//           },
//         },
//         {
//           path: '/manufacturingStatistics',
//           name: 'manufacturingStatistics',
//           component: (resolve) => require(['@/pages/statisticalForm/manufacturingStatistics'], resolve),
//           meta: {
//             title: '生产统计',
//           },
//         },
//         {
//           path: '/machineReport',
//           name: 'machineReport',
//           component: (resolve) => require(['@/pages/statisticalForm/machineReport'], resolve),
//           meta: {
//             title: '调机报表',
//           },
//         },
//         {
//           path: '/machineReport/detail',
//           name: 'machineReportDetail',
//           component: (resolve) => require(['@/pages/statisticalForm/machineReport/debugHistory'], resolve),
//           meta: {
//             title: '调机详情',
//           },
//         },
//         {
//           path: '/policeStatistics',
//           name: 'policeStatistics',
//           component: (resolve) => require(['@/pages/statisticalForm/policeStatistics'], resolve),
//           meta: {
//             title: '报警统计',
//           },
//         },
//         {
//           path: '/alarmHistory(old)',
//           name: 'alarmHistory(old)',
//           component: (resolve) => require(['@/pages/statisticalForm/alarmHistory(old)'], resolve),
//           meta: {
//             title: '报警历史',
//           },
//         },
//         {
//           path: '/deviceInfo',
//           name: 'deviceInfo',
//           component: (resolve) => require(['@/pages/DeviceInfo/deviceInfo'], resolve),
//           meta: {
//             title: '设备监控',
//           },
//         },
//         {
//           path: '/deviceInfo/debugMachineHistory',
//           name: 'debugMachineHistory',
//           component: (resolve) => require(['@/pages/DeviceInfo/debugMachineHistory'], resolve),
//           meta: {
//             title: '调机历史',
//           },
//         },
//         {
//           path: '/deviceInfo/productionDetails',
//           name: 'productionDetails',
//           component: (resolve) => require(['@/pages/DeviceInfo/productionDetails'], resolve),
//           meta: {
//             title: '生产详情',
//           },
//         },
//         {
//           path: '/deviceInfo/debugHistory',
//           name: 'debugHistory',
//           component: (resolve) => require(['@/pages/DeviceInfo/debugHistory'], resolve),
//           meta: {
//             title: '调机历史',
//           },
//         },
//         {
//           path: '/deviceInfo/logInfo',
//           // alias: "/logInfo",
//           name: 'logInfo',
//           // redirect: "/logInfo",
//           component: () => import('@/pages/logInfo'),
//           meta: {
//             title: '日志信息',
//           },
//         },
//         {
//           path: '/deviceInfo/yieldDetails',
//           // alias: "/logInfo",
//           name: 'yieldDetailss',
//           // redirect: "/logInfo",
//           component: () => import('@/pages/DeviceInfo/yieldDetails'),
//           meta: {
//             title: '机床产量',
//           },
//         },
//         {
//           path: '/deviceInfo/logInfo',
//           // alias: "/logInfo",
//           name: 'logInfo',
//           // redirect: "/logInfo",
//           component: () => import('@/pages/logInfo'),
//           meta: {
//             title: '日志信息',
//           },
//         },
//         {
//           path: '/deviceInfo/dataMonitor',
//           name: 'dataMonitor',
//           component: () => import('@/pages/dataMonitor'),
//           meta: {
//             title: '指令域心电图',
//           },
//         },
//       ],
//     },
//     {
//       path: '*',
//       name: '404',
//       component: () => import('@/pages/404/404'),
//     },
//   ],
// });
